﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSRI.HelperClasses;
using MSRI.SmsService;
using System.Configuration;
using System.IO;

namespace PgMobileSMSService
{
    public sealed class SMSClass
    {
        static SMSClass instance = null;
        static readonly object padlock = new object();
        public SmsServiceClass SmsService = null;

        SMSClass()
        {
            SmsService = new SmsServiceClass("SMS_ServicePGMobile");
            SmsService.OnDeliveryReportReceived += new OnDeliveryReportDelegate(SmsService_OnDeliveryReportReceived);
            SmsService.OnSmsReceived += new OnSmsReceivedDelegate(SmsService_OnSmsReceived);
        }

        public static SMSClass Instance
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new SMSClass();
                    }
                    return instance;
                }
            }
        }

        //
        // Your Code for Processing a received Sms goes here
        //
        SmsResponseClass SmsService_OnSmsReceived(SmsClass SmsMessage)
        {
            //Aca se invoca para que sea procesado por la app BizTalk
            ReferenciaOrquestacion.WebService_OrquestacionesSoapClient cliente = new PgMobileSMSService.ReferenciaOrquestacion.WebService_OrquestacionesSoapClient();
            ReferenciaOrquestacion.SMS sms = new PgMobileSMSService.ReferenciaOrquestacion.SMS();
            sms.Mensaje = SmsMessage.Body;
            sms.Numero = SmsMessage.Number;
            cliente.Operation_1(sms);

            string smsFileName = ConfigurationManager.AppSettings["smsFilePath"] + SmsMessage.Number + ".txt";
            StreamWriter sw = new StreamWriter(smsFileName);
            sw.Write(SmsMessage.Body);

            //sw.Close();
            // Compose a Response a list of Response Message and return back the Array Class
            // Please do not use SmsService.SendSms() Function to send message from this function
            SmsResponseClass Response = new SmsResponseClass();
            SmsClass SmsItem = new SmsClass();

            SmsItem.Body = "Recibimos " + SmsMessage.Body;
            SmsItem.Number = SmsMessage.Number;
            Response.AddResponseSms(SmsItem);
            return Response;
        }

        //
        // Your Code for Processing a deliveryreport goes here
        //
        void SmsService_OnDeliveryReportReceived(DeliveryReportClass DeliveryReport)
        {
            if (DeliveryReport.Status == DeliveryStatusEnum.Sent)
            {
                // Message Sent
            }
            else
            {
                // Message Sent Failed, You may want to retry
            }
        }

    }

}
